package flc.ast.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.midi.lib.mid.MidiFile;
import com.stark.midi.lib.model.MidFileBean;
import com.stark.midi.lib.model.MidFileProvider;
import com.stark.midi.lib.model.MidImportFileManager;
import com.stark.piano.lib.widget.PianoSongPlayer;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.PianoTrainActivity;
import flc.ast.activity.SelAudioActivity;
import flc.ast.adapter.HotMusicAdapter;
import flc.ast.adapter.MusicAdapter;
import flc.ast.bean.MyCollectBean;
import flc.ast.databinding.FragmentMusicBinding;
import flc.ast.dialog.RecordMoreDialog;
import flc.ast.dialog.TypeDialog;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IOUtil;
import stark.common.basic.utils.UriUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MusicFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MusicFragment extends BaseNoModelFragment<FragmentMusicBinding> {

    private MusicAdapter musicAdapter;
    private List<Integer> mAllIconList = new ArrayList<>();
    private List<Integer> mHotIconList = new ArrayList<>();
    private List<Integer> mChildrenSongIconList = new ArrayList<>();
    private List<Integer> mMoreIconList = new ArrayList<>();
    private List<Integer> mDanceIconList = new ArrayList<>();
    private List<Integer> mClassicIconList = new ArrayList<>();
    private BasePopupView popup;

    @Override
    protected int onCreate() {
        return R.layout.fragment_music;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        mDataBinding.ivMusicImport.setOnClickListener(this);
        mDataBinding.ivMusicType.setOnClickListener(this);
        mDataBinding.rvMusicList.setLayoutManager(new GridLayoutManager(mContext, 2));
        musicAdapter = new MusicAdapter();
        mDataBinding.rvMusicList.setAdapter(musicAdapter);
        musicAdapter.addChildClickViewIds(R.id.ivMusicItemCollect);
        musicAdapter.setOnItemChildClickListener(this);
        musicAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivMusicImport://导入曲目
                Intent intent = new Intent(getContext(), SelAudioActivity.class);
                startActivityForResult(intent, 120);
                break;
            case R.id.ivMusicType://曲目类型
                if (popup == null) {
                    TypeDialog typeDialog = new TypeDialog(mContext);
                    popup = new XPopup.Builder(mContext)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .atView(v)
                            .popupPosition(PopupPosition.Bottom)
                            .hasShadowBg(false) // 去掉半透明背景
                            .asCustom(typeDialog);
                    typeDialog.setListener(new TypeDialog.IListener() {
                        @Override
                        public void onClick(int position) {
                            mDataBinding.rvMusicList.setVisibility(View.VISIBLE);
                            mDataBinding.ivNoData.setVisibility(View.GONE);
                            switch (position) {
                                case 0:
                                    List<MidFileBean> list = new ArrayList<>();
                                    list.addAll(MidFileProvider.getHot());
                                    list.addAll(MidFileProvider.getChildrenSong());
                                    list.addAll(MidFileProvider.getClassic());
                                    list.addAll(MidFileProvider.getDance());
                                    list.addAll(MidFileProvider.getMore());
                                    list.addAll(MidImportFileManager.getInstance().getFileBeanList());
                                    musicAdapter.setIconList(mAllIconList);
                                    musicAdapter.setList(list);
                                    break;
                                case 1:
                                    musicAdapter.setIconList(mHotIconList);
                                    musicAdapter.setList(MidFileProvider.getHot());
                                    break;
                                case 2:
                                    musicAdapter.setIconList(mChildrenSongIconList);
                                    musicAdapter.setList(MidFileProvider.getChildrenSong());
                                    break;
                                case 3:
                                    musicAdapter.setIconList(mClassicIconList);
                                    musicAdapter.setList(MidFileProvider.getClassic());
                                    break;
                                case 4:
                                    musicAdapter.setIconList(mDanceIconList);
                                    musicAdapter.setList(MidFileProvider.getDance());
                                    break;
                                case 5:
                                    musicAdapter.setIconList(mMoreIconList);
                                    musicAdapter.setList(MidFileProvider.getMore());
                                    break;
                                case 6:
                                    List<MidFileBean> fileBeanList = MidImportFileManager.getInstance().getFileBeanList();
                                    if (fileBeanList.size() == 0) {
                                        mDataBinding.ivNoData.setVisibility(View.VISIBLE);
                                        mDataBinding.rvMusicList.setVisibility(View.GONE);
                                    }
                                    musicAdapter.setIconList(null);
                                    musicAdapter.setList(fileBeanList);
                                    break;
                            }
                        }
                    });
                }
                popup.show();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivMusicItemCollect:
                MidFileBean bean = musicAdapter.getItem(position);
                if (bean.isSelected()) {
                    List<MyCollectBean> listSp = AppSpUtils.getSongCollectionList();
                    for (MyCollectBean myCollectBean : listSp) {
                        if (myCollectBean.getMidFileBean().equals(bean)){
                            listSp.remove(myCollectBean);
                        }
                    }
                    AppSpUtils.saveSongCollectionList(listSp);
                } else {
                    List<MyCollectBean> listSave = new ArrayList<>();
                    MyCollectBean myCollectBean;
                    if (musicAdapter.getHotIconList() == null || position >= musicAdapter.getHotIconList().size()) {
                        myCollectBean = new MyCollectBean(R.drawable.w1, musicAdapter.getItem(position));
                    } else {
                        myCollectBean = new MyCollectBean(musicAdapter.getHotIconList().get(position), musicAdapter.getItem(position));
                    }
                    listSave.add(myCollectBean);
                    List<MyCollectBean> listSp = AppSpUtils.getSongCollectionList();
                    if (listSp != null && listSp.size() > 0) {
                        listSp.addAll(listSave);
                        AppSpUtils.saveSongCollectionList(listSp);
                    } else {
                        AppSpUtils.saveSongCollectionList(listSave);
                    }
                }
                musicAdapter.notifyItemChanged(position);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PianoTrainActivity.pianoTrainMode = PianoSongPlayer.Mode.APPRECIATE;
        PianoTrainActivity.playFileBean = musicAdapter.getItem(position);
        startActivity(PianoTrainActivity.class);
    }

    @Override
    protected void initData() {
        getHotIconData();
        getChildrenSongIconData();
        getClassicIconData();
        getDanceData();
        getMoreData();
        mAllIconList.addAll(mHotIconList);
        mAllIconList.addAll(mChildrenSongIconList);
        mAllIconList.addAll(mClassicIconList);
        mAllIconList.addAll(mDanceIconList);
        mAllIconList.addAll(mMoreIconList);
        musicAdapter.setIconList(mHotIconList);
        musicAdapter.setList(MidFileProvider.getHot());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onResume() {
        super.onResume();
        musicAdapter.notifyDataSetChanged();
    }

    private void getHotIconData() {
        mHotIconList.add(R.drawable.r1);
        mHotIconList.add(R.drawable.r2);
        mHotIconList.add(R.drawable.r3);
        mHotIconList.add(R.drawable.r4);
        mHotIconList.add(R.drawable.r5);
        mHotIconList.add(R.drawable.r6);
        mHotIconList.add(R.drawable.r7);
        mHotIconList.add(R.drawable.r8);
        mHotIconList.add(R.drawable.r9);
        mHotIconList.add(R.drawable.r10);
        mHotIconList.add(R.drawable.r11);
        mHotIconList.add(R.drawable.r12);
        mHotIconList.add(R.drawable.r13);
        mHotIconList.add(R.drawable.r14);
        mHotIconList.add(R.drawable.r15);
        mHotIconList.add(R.drawable.r16);
    }

    private void getChildrenSongIconData() {
        mChildrenSongIconList.add(R.drawable.e1);
        mChildrenSongIconList.add(R.drawable.e2);
        mChildrenSongIconList.add(R.drawable.e3);
        mChildrenSongIconList.add(R.drawable.e4);
        mChildrenSongIconList.add(R.drawable.e5);
        mChildrenSongIconList.add(R.drawable.e6);
        mChildrenSongIconList.add(R.drawable.e7);
        mChildrenSongIconList.add(R.drawable.e8);
        mChildrenSongIconList.add(R.drawable.e9);
        mChildrenSongIconList.add(R.drawable.e10);
        mChildrenSongIconList.add(R.drawable.e11);
        mChildrenSongIconList.add(R.drawable.e12);
        mChildrenSongIconList.add(R.drawable.e13);
        mChildrenSongIconList.add(R.drawable.e14);
        mChildrenSongIconList.add(R.drawable.e15);
        mChildrenSongIconList.add(R.drawable.e16);
    }

    private void getMoreData() {
        mMoreIconList.add(R.drawable.d1);
        mMoreIconList.add(R.drawable.d2);
        mMoreIconList.add(R.drawable.d3);
        mMoreIconList.add(R.drawable.d4);
        mMoreIconList.add(R.drawable.d5);
        mMoreIconList.add(R.drawable.d6);
        mMoreIconList.add(R.drawable.d7);
        mMoreIconList.add(R.drawable.d8);
        mMoreIconList.add(R.drawable.d9);
        mMoreIconList.add(R.drawable.d10);
        mMoreIconList.add(R.drawable.d11);
        mMoreIconList.add(R.drawable.d12);
        mMoreIconList.add(R.drawable.d13);
        mMoreIconList.add(R.drawable.d14);
        mMoreIconList.add(R.drawable.d15);
        mMoreIconList.add(R.drawable.d16);
    }

    private void getDanceData() {
        mDanceIconList.add(R.drawable.f1);
        mDanceIconList.add(R.drawable.f2);
        mDanceIconList.add(R.drawable.f3);
        mDanceIconList.add(R.drawable.f4);
        mDanceIconList.add(R.drawable.f5);
        mDanceIconList.add(R.drawable.f6);
        mDanceIconList.add(R.drawable.f7);
        mDanceIconList.add(R.drawable.f8);
        mDanceIconList.add(R.drawable.f9);
        mDanceIconList.add(R.drawable.f10);
        mDanceIconList.add(R.drawable.f11);
        mDanceIconList.add(R.drawable.f12);
        mDanceIconList.add(R.drawable.f13);
        mDanceIconList.add(R.drawable.f14);
        mDanceIconList.add(R.drawable.f15);
        mDanceIconList.add(R.drawable.f16);
    }

    private void getClassicIconData() {
        mClassicIconList.add(R.drawable.j1);
        mClassicIconList.add(R.drawable.j2);
        mClassicIconList.add(R.drawable.j3);
        mClassicIconList.add(R.drawable.j4);
        mClassicIconList.add(R.drawable.j5);
        mClassicIconList.add(R.drawable.j6);
        mClassicIconList.add(R.drawable.j7);
        mClassicIconList.add(R.drawable.j8);
        mClassicIconList.add(R.drawable.j9);
        mClassicIconList.add(R.drawable.j10);
        mClassicIconList.add(R.drawable.j11);
        mClassicIconList.add(R.drawable.j12);
        mClassicIconList.add(R.drawable.j13);
        mClassicIconList.add(R.drawable.j14);
        mClassicIconList.add(R.drawable.j15);
        mClassicIconList.add(R.drawable.j16);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 120) {
            String uri = data.getStringExtra(Content.videoUri);
            List<MidFileBean> fileBeanList = new ArrayList<>();
            fileBeanList.add(createFromUri(Uri.parse(uri)));
            MidImportFileManager.getInstance().addMidFileBeans(fileBeanList);
        }
    }

    private MidFileBean createFromUri(Uri uri) {
        try {
            InputStream inputStream = getContext().getContentResolver().openInputStream(uri);
            MidiFile midiFile = new MidiFile(inputStream);
            IOUtil.close(inputStream);
            if (midiFile.getTrackCount() <= 0) {
                //非正常的mid文件
                return null;
            }

            MidFileBean fileBean = new MidFileBean();
            fileBean.setFileUriStr(uri.toString());
            File file = UriUtils.uri2File(uri);
            if (file != null) {
                fileBean.setFileName(FileUtils.getFileNameNoExtension(file));
            } else {
                fileBean.setFileName(UriUtil.getFileNameByUri(uri));
            }
            return fileBean;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}